package com.umeox.iqibla.azkar.ui

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.view.View
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import com.umeox.iqibla.azkar.R
import com.umeox.iqibla.azkar.db.AppDatabase
import com.umeox.iqibla.azkar.db.Azkar
import com.umeox.iqibla.azkar.db.AzkarDao
import com.umeox.iqibla.azkar.receiver.UnbindReceiver
import com.umeox.iqibla.azkar.utils.DateUtils
import com.umeox.iqibla.azkar.utils.LongClickUtils
import com.umeox.iqibla.azkar.utils.OnNoDoubleClickListener
import com.umeox.iqibla.azkar.utils.SPUtils
import com.umeox.moto.common.executor.ThreadExecutor
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.app.ThemeManager
import com.umeox.moto.watch.themes.util.MetricsUtils
import com.umeox.moto.watch.themes.widget.ImageView
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.apiclient.model.ChantsCountDTO
import com.umeox.watch.moto.dataservice.DataProvider
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy

class MainActivity : ThemeAppCompatActivity() {

    private lateinit var mCountResultTv: TextView
    private lateinit var mCountIv: View
    private lateinit var mResetIv: View
    private lateinit var mBead1: ImageView
    private lateinit var mBead2: ImageView
    private lateinit var mBead3: ImageView
    private lateinit var mBead4: ImageView
    private lateinit var mBead5: ImageView
    private lateinit var mLineView: View //中间线条

    private var mCount: Int = 0
    private var mTodayAzkarCount: Int = 0

    //处理跨天的变量，存储昨天的内存缓存数据
    private var mYesterdayAzkarCount: Int = 0

    private lateinit var azkarDao: AzkarDao

    private var mCurrentStyleIndex = 0

    private lateinit var animatorSet: AnimatorSet


    private val BEAD_ICONS = intArrayOf(
        R.drawable.bead_style_1,
        R.drawable.bead_style_2,
        R.drawable.bead_style_3,
        R.drawable.bead_style_4,
        R.drawable.bead_style_5,
        R.drawable.bead_style_6
    )

    private val LINE_COLORS = intArrayOf(
        Color.parseColor("#BCFFD1"),
        Color.parseColor("#FFFFFF"),
        Color.parseColor("#8D5F0B"),
        Color.parseColor("#FFEA83"),
        Color.parseColor("#20AAB2"),
        Color.parseColor("#FFFFFF")
    )

    private val LINE_COLORS_LIGHT_THEME = intArrayOf(
        Color.parseColor("#2EC26C"),
        Color.parseColor("#9E9F9D"),
        Color.parseColor("#8D5F0B"),
        Color.parseColor("#FFEA83"),
        Color.parseColor("#20AAB2"),
        Color.parseColor("#9E9F9D")
    )


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        azkarDao = AppDatabase.get().azkarDao()
        mCurrentStyleIndex = SPUtils.getInt(this, SPUtils.KEY_CURRENT_STYLE, 0)
        mCountResultTv = findViewById(R.id.tv_count_result)
        mCountIv = findViewById(R.id.ll_count)
        mResetIv = findViewById(R.id.iv_reset)
        mResetIv.isHapticFeedbackEnabled = false

        mBead1 = findViewById(R.id.iv_bead1)
        mBead2 = findViewById(R.id.iv_bead2)
        mBead3 = findViewById(R.id.iv_bead3)
        mBead4 = findViewById(R.id.iv_bead4)
        mBead5 = findViewById(R.id.iv_bead5)
        mLineView = findViewById(R.id.line_view)

        setUIStyle(mCurrentStyleIndex)


        mCountIv.setOnClickListener(object : OnNoDoubleClickListener() {

            override fun onNoDoubleClick(v: View?) {
                //执行动画
                animatorSet.start()
            }
        })



        mCountIv.setOnLongClickListener {
            if (mCurrentStyleIndex == 5) {
                mCurrentStyleIndex = -1
            }
            mCurrentStyleIndex++
            setUIStyle(mCurrentStyleIndex)
            SPUtils.setInt(mContext, SPUtils.KEY_CURRENT_STYLE, mCurrentStyleIndex)
            true
        }

        LongClickUtils.setLongClick(Handler(), mResetIv, 3000L) {
            vibrate(300)
            mCount = 0
            mTodayAzkarCount =
                AppDatabase.get().azkarDao().queryTodayAzkarCount(DateUtils.getTodayMillis())
            mCountResultTv.text = "0"
            //上报赞念数据
            uploadChants()
            true
        }

        if (DateUtils.getTodayMillis() > azkarDao.queryLatestRecordTodayMillis()
        ) {
            azkarDao.save(Azkar(DateUtils.getTodayMillis(), 0, false))
        }
        mTodayAzkarCount = azkarDao.queryTodayAzkarCount(DateUtils.getTodayMillis())
        initAnimatorSet()

        findViewById<ImageView>(R.id.iv_history).setOnClickListener {
            startActivity(Intent(this@MainActivity, HistoryActivity::class.java))
        }

    }

    private fun initAnimatorSet() {
        val translation: Float = MetricsUtils.convertDpToPixel(this, 66F)
        val translation1: Float = MetricsUtils.convertDpToPixel(this, 86F)
        animatorSet = AnimatorSet()
        animatorSet.interpolator = FastOutLinearInInterpolator()
        animatorSet.setDuration(50)
        animatorSet.setupStartValues()
        animatorSet.playTogether(
            ObjectAnimator.ofFloat(mBead1, "translationY", translation),
            ObjectAnimator.ofFloat(mBead2, "translationY", translation),
            ObjectAnimator.ofFloat(mBead3, "translationY", translation),
            ObjectAnimator.ofFloat(mBead4, "translationY", translation1),
            ObjectAnimator.ofFloat(mBead5, "translationY", translation1)
        )
        animatorSet.addListener(object : Animator.AnimatorListener {

            override fun onAnimationStart(animation: Animator) {
            }

            override fun onAnimationEnd(animation: Animator) {
                mBead1.translationY = 0f
                mBead2.translationY = 0f
                mBead3.translationY = 0f
                mBead4.translationY = 0f
                mBead5.translationY = 0f

//                vibrate(50)
                mCount++
                mCountResultTv.text = "$mCount"
                saveAzkarCount()
            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }
        })
    }

    private fun setUIStyle(mCurrentStyleIndex: Int) {
        mBead1.setImageResource(BEAD_ICONS[mCurrentStyleIndex])
        mBead2.setImageResource(BEAD_ICONS[mCurrentStyleIndex])
        mBead3.setImageResource(BEAD_ICONS[mCurrentStyleIndex])
        mBead4.setImageResource(BEAD_ICONS[mCurrentStyleIndex])
        mBead5.setImageResource(BEAD_ICONS[mCurrentStyleIndex])
        mLineView.setBackgroundColor(if (ThemeManager.getInstance().currentTheme == 1)
            LINE_COLORS_LIGHT_THEME[mCurrentStyleIndex]
        else LINE_COLORS[mCurrentStyleIndex])
    }

    private fun vibrate(milliseconds: Long) {
        val mVibrator = mContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        mVibrator.vibrate(milliseconds)
    }

    private fun saveAzkarCount() {
        val needSaveCount: Int
        if (DateUtils.getTodayMillis() > azkarDao.queryLatestRecordTodayMillis()
        ) {
            needSaveCount = mCount + mTodayAzkarCount - azkarDao.queryLatestRecordCount()
            mYesterdayAzkarCount = azkarDao.queryLatestRecordCount() - mTodayAzkarCount
            if (mTodayAzkarCount > 0) {
                mTodayAzkarCount = 0
            }
        } else {
            needSaveCount = mCount - mYesterdayAzkarCount + mTodayAzkarCount
        }
        azkarDao.save(Azkar(DateUtils.getTodayMillis(), needSaveCount, false))
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mCount + mTodayAzkarCount > 0) {
            val dbTodayAzkar = azkarDao.queryByTodayMillis(DateUtils.getTodayMillis())
            if (dbTodayAzkar != null) { //特殊情况，停在此界面跨天
                Logger.e("dbTodayAzkar=$dbTodayAzkar,(mCount + mTodayAzkarCount)=${mCount + mTodayAzkarCount}")
                if (dbTodayAzkar.count < (mCount + mTodayAzkarCount)) {
                    azkarDao.save(
                        Azkar(
                            DateUtils.getTodayMillis(),
                            mCount + mTodayAzkarCount,
                            false
                        )
                    )
                }
            }
        }
        sendBroadcast(Intent(UnbindReceiver.ACTION_UPLOAD_CHANTS))
    }


    private fun uploadChants() {
        if (!DataProvider.isActivated()) {
            return
        }
        ThreadExecutor.getInstance().io().execute {
            //查询出所有没有上传的数据
            val azkarDao = AppDatabase.get().azkarDao()
            val notUploadAzkarList = azkarDao.loadNoUploadList()
            notUploadAzkarList?.apply {
                val chantsCountDTOList = mutableListOf<ChantsCountDTO>()
                notUploadAzkarList.forEach {
                    val chantsCountDTO = ChantsCountDTO()
                    chantsCountDTO.date = com.umeox.moto.common.utils.DateUtils.formatDateTime(
                        it.todayMillis * 1000L,
                        "yyyyMMddZ"
                    )
                    chantsCountDTO.amount = it.count
                    chantsCountDTOList.add(chantsCountDTO)
                }
                if (chantsCountDTOList.isNotEmpty()) {
                    val result = PullApiClientProxy.fetchBinder().uploadChants(chantsCountDTOList)
                    Logger.e(if (result) "赞念计数上传成功" else "赞念计数上传失败")
                    //更新本地数据库的上传标记为已上传
                    if (result) {
                        notUploadAzkarList.forEach {
                            it.isUpload = true
                            azkarDao.save(notUploadAzkarList)
                        }
                    }
                }
            }
        }
    }

}
